<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\ChargeDetail;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Distributors;
use Hyperf\Redis\Redis;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;

class ChargeOptionController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected ChargeOption $chargeOption;



    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**套餐列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit','keyword','distributor_id','is_autoload','mode']);
        $data['list'] = $this->chargeOption->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
//                $query->orWhere('content', 'like', '%'.$page['keyword'].'%');
            }
            if($page['mode'] == 'self'){
                $query->where('distributor_id',0);
            }else{
                if($page['distributor_id']){
                    $query->where('distributor_id',$page['distributor_id']);
                }else{
                    $query->where('distributor_id', '>',0);
                }
            }
            if($page['is_autoload'] !== ''){
                $query->where('is_autoload',$page['is_autoload']);
            }
            $query->where('is_del', 1);
        })->orderBy('sort', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get()->toArray();
        $data['total']= $this->chargeOption->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
            }
            if($page['mode'] == 'self'){
                $query->where('distributor_id',0);
            }else{
                if($page['distributor_id']){
                    $query->where('distributor_id',$page['distributor_id']);
                }else{
                    $query->where('distributor_id', '>',0);
                }
            }
            if($page['is_autoload'] !== ''){
                $query->where('is_autoload',$page['is_autoload']);
            }
            $query->where('is_del', 1);
        })->count();
        foreach($data['list'] as $k => $v){
            if($data['list'][$k]['distributor_id'] > 0 ){
                $data['list'][$k]['distributor_name'] = Distributors::where('id',$v['distributor_id'])->value('name');
            }else{
                $data['list'][$k]['distributor_name'] = '默认套餐';
            }
            $data['list'][$k]['power_children'] = ChargeDetail::where('charge_option_id',$v['id'])
            ->where('type',1)
//                ->where('is_del',1)
            ->orderBy('sort','desc')->get()->toArray();
            $data['list'][$k]['time_children'] = ChargeDetail::where('charge_option_id',$v['id'])
            ->where('type',2)
//                ->where('is_del',1)
            ->orderBy('sort','desc')->get()->toArray();
        }
        return $this->success($data);
    }


    /**创建
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $data = $request->post();
        if(isset($data['distributor_name'])){
            unset($data['distributor_name']);
        }
        if(isset($data['power_children'])){
            unset($data['power_children']);
        }
        if(isset($data['time_children'])){
            unset($data['time_children']);
        }
        if (array_key_exists('id',$data) && $data['id'] > 0) {
            $id = $data['id'];
            unset($data['id']);
            if(array_key_exists('updated_at', $data)){
                unset($data['updated_at']);
            }
            $this->chargeOption->where('id', $id)->update($data);
        } else {
            ChargeOption::create($data);
        }
        return $this->success();
    }

    /**删除
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        Db::beginTransaction();
        try{
            $id = $request->input('id',0,'int');
            if (!$id) {
                return $this->error(ErrorCode::PARAMS_ERR);
            }
            $this->chargeOption->where('id',$id)->update(['is_del'=>0]);
            ChargeDetail::where('charge_option_id',$id)->update(['is_del'=>0]);
            Device::where('charge_id',$id)->update(['charge_id'=>0]);
            Db::commit();
        return $this->success();
        }catch (\Exception $e){
            Db::rollBack();
            return $this->error(code:1001,msg:'操作繁忙请稍后重试');
        }
    }

}
